package com.erp.shop.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.shop.domain.bo.ErpSellerStoreEmpowerExtendBo;
import com.erp.shop.mapper.ErpSellerStoreEmpowerExtendMapper;
import com.erp.shop.mapper.ErpSellerStoreEmpowerMapper;
import com.erp.shop.mapper.ErpSellerStoreSubcategoryMapper;
import com.erp.shop.mapper.ErpStoreCategoryBrandMapper;
import com.erp.shop.service.IErpSellerStoreEmpowerExtendService;
import com.erp.shop.service.IErpSellerStoreEmpowerService;
import com.ruoyi.ae.api.RemoteAeCategoryService;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.ae.api.RemoteAeStoreInfoService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.HttpSendUtils;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.UrlConfig;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.gather.api.domain.Aliexpress;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpowerExtend;
import com.ruoyi.shop.api.domain.ErpSellerStoreSubcategory;
import com.ruoyi.shop.api.domain.ErpStoreCategoryBrand;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Validated
@RequiredArgsConstructor

@RestController
@RequestMapping("/store/auth")
public class ErpSellerStoreAuthController extends BaseController {
    private static String ACCESS_TOKEN_KEY = "access_token_key:";

    @Autowired
    RestTemplate restTemplate;
    private final IErpSellerStoreEmpowerService iErpSellerStoreEmpowerService;
    private final ErpSellerStoreEmpowerMapper erpSellerStoreEmpowerMapper;
    private final IErpSellerStoreEmpowerExtendService iErpSellerStoreEmpowerExtendService;
    private final ErpSellerStoreEmpowerExtendMapper empowerExtendMapper;
    private final ErpSellerStoreSubcategoryMapper erpSellerStoreSubcategoryMapper;
    private final ErpStoreCategoryBrandMapper erpStoreCategoryBrandMapper;
    private final RemoteAeStoreInfoService remoteAeStoreInfoService;
    private final RemoteAeProductService remoteAeProductService;
    private final RemoteAeCategoryService remoteAeCategoryService;


    @GetMapping("/getAccessToken")
    public R<Object> getAccessToken(Long storeId, String code) {
        R<Object> accessTokenInfo = remoteAeStoreInfoService.getAccessTokenInfo(storeId, code);
        String body = JSONObject.toJSONString(accessTokenInfo.getData());
        // 根据code获取access_token
//        ResponseEntity<String> forEntity = restTemplate
//                .getForEntity(aeConfig.getEndpoint() + "/ae/auth/getAccessToken?storeId=" + storeId + "&code=" + code, String.class);
//        String body = (String) forEntity.getBody();

        Dict parseMap = JsonUtils.parseMap(body);

        // 获取是否授权成功
        Integer code1 = parseMap.getInt("code");
        if (code1.equals(200)) {
            Dict dataMap = JsonUtils.parseMap(parseMap.getStr("data"));
            ErpSellerStoreEmpower empower = iErpSellerStoreEmpowerService.queryByStoreId(storeId);
            if (empower != null) {
                if ("0".equals(empower.getIsEmpower())) {
                    Thread thread = new Thread(
                            new Runnable() {
                                @Override
                                public void run() {
                                    getStoreUsableBrand(storeId);
                                }
                            }
                    );
                    thread.start();
                }
                // 修改授权状态
                empower.setIsEmpower("1");
                empower.setEmpowerTime(new Date());
                // 过期时间
                Long expire_time = Long.valueOf(dataMap.get("expire_time").toString());
                DateTime expireTime = new DateTime(expire_time);
                empower.setExpireTime(expireTime.toDate());
                erpSellerStoreEmpowerMapper.updateById(empower);
                //将授权信息保存至表中
                ErpSellerStoreEmpowerExtend empowerExtend = iErpSellerStoreEmpowerExtendService.queryBySellerId(storeId);
                //将之前的该店铺的授权信息全部置为0
//                iErpSellerStoreEmpowerExtendService.failureToken(empower.getId());
                if (empowerExtend == null)
                    empowerExtend = new ErpSellerStoreEmpowerExtend();
                System.out.println(dataMap);
                empowerExtend.setSellerId(storeId);
                empowerExtend.setExpiresIn(Long.valueOf(dataMap.get("expires_in").toString()));
                empowerExtend.setUserId((String) dataMap.get("user_id"));
                empowerExtend.setUserNick((String) dataMap.get("user_nick"));
                empowerExtend.setHavanaId((String) dataMap.get("havana_id"));
                empowerExtend.setAccountPlatform((String) dataMap.get("account_platform"));
                empowerExtend.setAccessToken((String) dataMap.get("access_token"));
                empowerExtend.setAccount((String) dataMap.get("account"));
                empowerExtend.setRefreshToken((String) dataMap.get("refresh_token"));
                empowerExtend.setRefreshExpiresIn(Long.valueOf(dataMap.get("refresh_expires_in").toString()));
                empowerExtend.setExpireTime(expire_time);
                empowerExtend.setRefreshTokenValidTime(Long.valueOf(dataMap.get("refresh_token_valid_time").toString()));
                empowerExtend.setSp((String) dataMap.get("sp"));
                empowerExtend.setLocale((String) dataMap.get("locale"));
                empowerExtend.setAccountId((String) dataMap.get("account_id"));
                empowerExtend.setType(1);

                empowerExtendMapper.insertOrUpdate(empowerExtend);
                querySellerStoreInfo(empower);
                //更新用户店铺一级类目
                ErpSellerStoreSubcategory subcategory = erpSellerStoreSubcategoryMapper.selectOne(
                        new LambdaQueryWrapper<ErpSellerStoreSubcategory>()
                                .eq(ErpSellerStoreSubcategory::getSellerStoreId, empower.getId())
                                .eq(ErpSellerStoreSubcategory::getUserId, empower.getUserId())
                );
                if (subcategory == null) {
                    subcategory = new ErpSellerStoreSubcategory();
                }
                subcategory.setSellerStoreId(empower.getId());
                subcategory.setUserId(empower.getUserId());
                String categoryTreeList = getCategoryTreeList(empower.getId());
                if (categoryTreeList != null) {
                    subcategory.setCategoryIds(categoryTreeList);
                    System.out.println(subcategory);
                    erpSellerStoreSubcategoryMapper.insertOrUpdate(subcategory);
                }

            }
            return R.ok("授权成功", parseMap.getStr("data"));
        } else {
            return R.fail("授权失败");
        }

    }

    public String getCategoryTreeList(Long storeId) {
        R<Object> objectOne = remoteAeProductService.categoryTreeListInnerAuth(0L, storeId);
        String body = (String) objectOne.getData();
        System.out.println(body);
        if (body.contains("未查到该店铺授权")) {
            return null;
        }
        String string = JSONObject.parseObject(body)
                .getJSONObject("aliexpress_category_tree_list_response")
                .getJSONObject("aeop_post_category_list")
                .getString("aeop_post_category");
//        Dict parseMap = JsonUtils.parseMap(body);
        JSONArray jsonArray = JSONArray.parseArray(string);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            stringBuffer.append(jsonObject.getString("id"));
//            System.out.println(i);
//            System.out.println(jsonArray.size());
//            System.out.println(jsonArray.size()-1);
            if (i != jsonArray.size() - 1) {
                stringBuffer.append(",");
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 授权时获取资质信息
     */
    @GetMapping("/querySellerStoreInfo")
    public void querySellerStoreInfo(ErpSellerStoreEmpower empower) {
        // 获取现在数据库中已授权的店铺id
        ErpSellerStoreEmpowerExtend erpSellerStoreEmpowerExtend = new ErpSellerStoreEmpowerExtend();
        ErpSellerStoreEmpowerExtendBo erpSellerStoreEmpowerExtendBo = new ErpSellerStoreEmpowerExtendBo();
        // 循环遍历，获取其最新信息
        Map<String, Object> map = new HashMap<>();
        map.put("sellerId", empower.getId());
        R<Object> accessTokenInfo = remoteAeStoreInfoService.querySellerStoreInfo(empower.getId().toString());
        String body = JSONObject.toJSONString(accessTokenInfo.getData());


//		ResponseEntity<String> forEntity = restTemplate
//				.postForEntity(aeConfig.getEndpoint() + "/erp/erpSellerStore/querySellerStoreInfo", map, String.class);
//		String body = (String) forEntity.getBody();
        JSONObject profile = JSONObject.parseObject(body);
        erpSellerStoreEmpowerExtend = iErpSellerStoreEmpowerExtendService.queryBySellerId(empower.getId());
        if (erpSellerStoreEmpowerExtend == null) {
            // 之前不存在，新增
            erpSellerStoreEmpowerExtend = new ErpSellerStoreEmpowerExtend();
        }
        erpSellerStoreEmpowerExtend.setUserNick(empower.getStoreUserName());
        erpSellerStoreEmpowerExtend.setSellerId(empower.getId());
        erpSellerStoreEmpowerExtend.setLimitStoreProductNumber(profile.getString("limit_store_product_number"));
        erpSellerStoreEmpowerExtend.setAuthStoreProductNumber(profile.getString("auth_store_product_number"));
        erpSellerStoreEmpowerExtend.setOnlineStoreProductNumber(profile.getString("online_store_product_number"));
        erpSellerStoreEmpowerExtend.setCountry(profile.getString("country"));
        erpSellerStoreEmpowerExtend.setQuotationCurrency(profile.getString("quotation_currency"));
        erpSellerStoreEmpowerExtend.setType(1);
        BeanUtils.copyProperties(erpSellerStoreEmpowerExtend, erpSellerStoreEmpowerExtendBo);
        // 修改
        iErpSellerStoreEmpowerExtendService.updateByBo(erpSellerStoreEmpowerExtendBo);

    }

    public R<Object> getStoreUsableBrand(Long storeId) {
        List<ErpSellerStoreEmpower> storeList = new ArrayList<>();
        //查询单个店铺
        if (storeId != null) {
            storeList = erpSellerStoreEmpowerMapper.selectListById(storeId);
        } else {
            storeList = erpSellerStoreEmpowerMapper.selectAllList();
        }
        for (ErpSellerStoreEmpower store : storeList) {
            List<ErpStoreCategoryBrand> list = new ArrayList<>();
            //验证店铺是否有授权
            storeId = store.getId();
            Map<String, Object> map = new HashMap<>();
            map.put("sellerId", storeId);
            R<Object> accessTokenInfo = remoteAeStoreInfoService.querySellerStoreInfo(storeId.toString());

//			ResponseEntity<String> forEntity = restTemplate
//					.postForEntity(aeConfig.getEndpoint() + "/erp/erpSellerStore/querySellerStoreInfo", map, String.class);
            String body = JSONObject.toJSONString(accessTokenInfo.getData());
            if (JSONObject.parseObject(body).getString("code").equals("500")) {
                continue;
            }
            //保存所有的
            Map<String, ErpStoreCategoryBrand> categoryList = new HashMap<>();
            //1、获取店铺一级类目
            //2、递归循环获取的一级类目，直到将翻到叶子节点
            categoryList = categoryTreeList(0L, storeId, categoryList);
            //3、将列表进行循环，调用方法，查询品牌
            for (String key : categoryList.keySet()) {
                ErpStoreCategoryBrand brand = (ErpStoreCategoryBrand) categoryList.get(key);
                List<Aliexpress.ValueVo> brandList = getBrandById(brand);
                for (Aliexpress.ValueVo value : brandList) {

                    ErpStoreCategoryBrand brandNew = new ErpStoreCategoryBrand();
                    BeanUtils.copyProperties(brand, brandNew);

                    brandNew.setBrandCnName(value.getZhName());
                    brandNew.setBrandId(value.getAttr_value_id());
                    brandNew.setBrandName(value.getAttr_value());
//                    ErpStoreCategoryBrand brandSel = erpStoreCategoryBrandMapper.selectOne(
//                            new LambdaQueryWrapper<ErpStoreCategoryBrand>()
//                                    .eq(ErpStoreCategoryBrand::getCategoryId, brand.getCategoryId())
//                                    .eq(ErpStoreCategoryBrand::getBrandId, brand.getBrandId())
//                                    .eq(ErpStoreCategoryBrand::getStoreId, brand.getStoreId())
//                    );
//                    if (brandSel != null) {
//                        brand.setId(brandSel.getId());
//                    }
                    list.add(brandNew);
                    System.out.println(brandNew);
                    // erpStoreCategoryBrandMapper.insertOrUpdate(brand);
                }
            }
            //根据店铺id删除已维护店铺品牌信息，再更新；
            erpStoreCategoryBrandMapper.delete(new LambdaQueryWrapper<ErpStoreCategoryBrand>().eq(ErpStoreCategoryBrand::getStoreId, storeId));
            erpStoreCategoryBrandMapper.insertBatch(list);
            System.out.println("店铺" + storeId + "同步成功");

        }

        return R.ok();
    }

    //获取店铺类目
    public Map<String, ErpStoreCategoryBrand> categoryTreeList(Long categoryId, Long storeId, Map<String, ErpStoreCategoryBrand> categoryMap) {
//        Map<String, Object> paremeterMap = new HashMap<>();
//        paremeterMap.put("category_id", categoryId);
//        paremeterMap.put("only_with_permission", "true");
        try {
//			//获取店铺的accessToken
//			ResponseEntity<String> forEntity = restTemplate
//					.getForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/categoryTreeList?categoryId=" + categoryId + "&sellerId=" + storeId, String.class);
//			String body = (String) forEntity.getBody();
            R<Object> objectR = remoteAeProductService.categoryTreeListInnerAuth(categoryId, storeId);
            String body = (String) objectR.getData();


//        System.out.println(body);
            String returnCategoryList = JSONObject.parseObject(body)
                    .getJSONObject("aliexpress_category_tree_list_response")
                    .getString("aeop_post_category_list");
            if (returnCategoryList == null || returnCategoryList.equals("{}")) {
                return categoryMap;
            }
            String string = JSONObject.parseObject(body)
                    .getJSONObject("aliexpress_category_tree_list_response")
                    .getJSONObject("aeop_post_category_list")
                    .getString("aeop_post_category");
//        Dict parseMap = JsonUtils.parseMap(body);
            JSONArray jsonArray = JSONArray.parseArray(string);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.getBoolean("isleaf")) {
                    //保存categoryId
                    ErpStoreCategoryBrand categoryBrand = new ErpStoreCategoryBrand();
                    categoryBrand.setStoreId(storeId);
                    categoryBrand.setCategoryId(jsonObject.getLong("id"));
                    String zh = JSONObject.parseObject(jsonObject.getString("names")).getString("zh");
                    String en = JSONObject.parseObject(jsonObject.getString("names")).getString("en");
                    categoryBrand.setCategoryCnName(zh);
                    categoryBrand.setCategoryEnName(en);
                    categoryBrand.setCategoryLevel(jsonObject.getString("level"));
                    categoryMap.put(categoryBrand.getCategoryId().toString(), categoryBrand);
                } else {
                    if (categoryMap == null) {
                        System.out.println("categoryList null");
                    }
                    categoryMap = categoryTreeList(jsonObject.getLong("id"), storeId, categoryMap);
//                System.out.println(categoryMap);
                }
            }
            return categoryMap;
        } catch (Exception e) {
            return categoryMap;
        }
    }

    public List<Aliexpress.ValueVo> getBrandById(ErpStoreCategoryBrand categoryBrand) {
        List<Aliexpress.ValueVo> values = new ArrayList<>();
        //出现异常，跳过
        try {
            R<Object> brandR = remoteAeCategoryService.getBrandByIdInnerAuth(categoryBrand.getCategoryId(), categoryBrand.getStoreId());
//			String res = HttpUtil.get(aeConfig.getEndpoint() + "/aliexpress/category/getBrandById?categoryId=" + categoryBrand.getCategoryId()
//					+ "&storeId=" + categoryBrand.getStoreId());
            JSONObject brando = JSONObject.parseObject((String) brandR.getData());

//			Aliexpress.AliexpressCategoryResponse aliexpressCategoryResponse = JSONObject.parseObject(brando,
//					Aliexpress.AliexpressCategoryResponse.class);
//			List<Aliexpress.AttributeDto> attributeDtoList = aliexpressCategoryResponse
//					.getAliexpressCategoryRedefiningGetchildattributesresultbypostcateidandpathResponse().getResult()
//					.getAttributes().getAeopAttributeDto();
            String aeopAttributeDto = brando.getJSONObject("aliexpress_category_redefining_getchildattributesresultbypostcateidandpath_response")
                    .getJSONObject("result")
                    .getJSONObject("attributes")
                    .getString("aeop_attribute_dto");
            List<Aliexpress.AttributeDto> attributeDtoList = JSONArray.parseArray(aeopAttributeDto, Aliexpress.AttributeDto.class);


            for (Aliexpress.AttributeDto attributeDto : attributeDtoList) {

                Long nameId = attributeDto.getId();
                if (nameId.equals(2l)) {

                    List<Aliexpress.AttrValueDto> attrValueDtoList = attributeDto.getValues().getAeopAttrValueDto();
                    if (attrValueDtoList != null) {
                        for (Aliexpress.AttrValueDto attrValueDto : attrValueDtoList) {
                            Aliexpress.ValueVo valueVo = new Aliexpress.ValueVo();

                            Map valueNames = JSONObject.parseObject(attrValueDto.getNames(), Map.class);
                            String enValueName = (String) valueNames.get("en");
                            String zhValueName = (String) valueNames.get("zh");

                            valueVo.setAttr_value_id(attrValueDto.getId());
                            valueVo.setZhName(zhValueName);
                            valueVo.setAttr_value(enValueName);
                            values.add(valueVo);
                        }
                    }
                }
            }
            return values;
        } catch (Exception e) {
            return values;
        }
    }

    /**
     * 获取店铺一级类目
     *
     * @return
     */
    @GetMapping("/getStorePowerCategory")
    public R<String> getStorePowerCategory(String storeUserName) {
        List<ErpSellerStoreEmpower> storeList = new ArrayList<>();
        if (ObjectUtils.isNull(storeUserName)) {
            //1、获得平台所有有权限的店铺
            storeList = erpSellerStoreEmpowerMapper.getIsEmpowerStore();
        } else {
            ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(storeUserName);
            if (Objects.isNull(store)) {
                return R.fail("店铺不存在");
            } else {
                storeList.add(store);
            }
        }

        //2、循环调用
        ErpSellerStoreSubcategory subcategory = new ErpSellerStoreSubcategory();
        for (ErpSellerStoreEmpower store : storeList) {
            subcategory = erpSellerStoreSubcategoryMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStoreSubcategory>()
                            .eq(ErpSellerStoreSubcategory::getSellerStoreId, store.getId())
                            .eq(ErpSellerStoreSubcategory::getUserId, store.getUserId())
            );
            if (subcategory == null) {
                subcategory = new ErpSellerStoreSubcategory();
            }
            subcategory.setSellerStoreId(store.getId());
            subcategory.setUserId(store.getUserId());
            String categoryTreeList = getCategoryTreeList(store.getId());
            if (categoryTreeList != null) {
                subcategory.setCategoryIds(categoryTreeList);
                System.out.println(subcategory);
                erpSellerStoreSubcategoryMapper.insertOrUpdate(subcategory);
            }
        }

        return R.ok("已更新");
    }


//	@GetMapping("/queryAllSellerStoreInfo")
//	public void queryAllSellerStoreInfo() {
//		// 获取现在数据库中已授权的店铺id
//		List<ErpSellerStoreEmpower> empowerList = iErpSellerStoreEmpowerService.getEmpowerStore();
//		ErpSellerStoreEmpowerExtend erpSellerStoreEmpowerExtend = new ErpSellerStoreEmpowerExtend();
//		ErpSellerStoreEmpowerExtendBo erpSellerStoreEmpowerExtendBo = new ErpSellerStoreEmpowerExtendBo();
//		for (ErpSellerStoreEmpower empower : empowerList) {
//			iErpSellerStoreEmpowerExtendService.failureToken(empower.getId());
//			// 循环遍历，获取其最新信息
//			int flag = 1;
//			Map<String, Object> map = new HashMap<>();
//			map.put("sellerId", empower.getId());
//			ResponseEntity<String> forEntity = restTemplate.postForEntity(
//					aeConfig.getEndpoint() + "/erp/erpSellerStore/querySellerStoreInfo", map, String.class);
//			String body = (String) forEntity.getBody();
//			JSONObject profile = JSONObject.parseObject(body).getJSONObject("msg");
//
//			erpSellerStoreEmpowerExtend = iErpSellerStoreEmpowerExtendService
//					.selectByUserNick(empower.getStoreUserName());
//			if (erpSellerStoreEmpowerExtend == null) {
//				// 之前不存在，新增
//				erpSellerStoreEmpowerExtend = new ErpSellerStoreEmpowerExtend();
//				flag = 0;
//			}
//			erpSellerStoreEmpowerExtend.setUserNick(empower.getStoreUserName());
//			erpSellerStoreEmpowerExtend.setSellerId(empower.getId());
//			erpSellerStoreEmpowerExtend.setLimitStoreProductNumber(profile.getString("limit_store_product_number"));
//			erpSellerStoreEmpowerExtend.setAuthStoreProductNumber(profile.getString("auth_store_product_number"));
//			erpSellerStoreEmpowerExtend.setOnlineStoreProductNumber(profile.getString("online_store_product_number"));
//			erpSellerStoreEmpowerExtend.setCountry(profile.getString("country"));
//			erpSellerStoreEmpowerExtend.setQuotationCurrency(profile.getString("quotation_currency"));
//			erpSellerStoreEmpowerExtend.setType(1);
//			BeanUtils.copyProperties(erpSellerStoreEmpowerExtend, erpSellerStoreEmpowerExtendBo);
//			if (flag == 1) {
//				// 修改
//				iErpSellerStoreEmpowerExtendService.updateByBo(erpSellerStoreEmpowerExtendBo);
//			} else {
//				// 新增
//				iErpSellerStoreEmpowerExtendService.insertByBo(erpSellerStoreEmpowerExtendBo);
//			}
//		}
//
//	}

    /**
     * 4.0品牌库授权
     */
    @GetMapping("/getStorePowerFromOldProject")
    public R<Object> getStorePowerFromOldProject(String storeUserName, Long userId) {
//        ResponseEntity<String> responseEntity = restTemplate.getForEntity("https://pbb2c.com/erp-api/gather/seller/sellerStoreEmpower?storeUserName=" + storeUserName, String.class);
//        String handle = "http://192.168.110.8:8860";
//        ResponseEntity<String> responseEntity = restTemplate.getForEntity(handle +"/seller/sellerStoreEmpower/queryStoreInfoByStoreUserName?storeUserName=" + storeUserName, String.class);
        String body = getReturnGetBody("https://pbb2c.com/erp-api/seller/sellerStoreEmpower/queryStoreInfoByStoreUserName?storeUserName=" + storeUserName);
        System.out.println(body);
//        String body = responseEntity.getBody();

        JSONObject jsonObject = JSONObject.parseObject(body).getJSONObject("data");
        //在老系统中查找store两个表，拿到信息
        ErpSellerStoreEmpower storeEmpower = jsonObject.getObject("storeEmpower", ErpSellerStoreEmpower.class);
        ErpSellerStoreEmpowerExtend storeEmpowerExtend = jsonObject.getObject("storeEmpowerExtend", ErpSellerStoreEmpowerExtend.class);
        //插入到store表中
        storeEmpower.setUserId(userId);
        storeEmpowerExtend.setSellerId(storeEmpower.getId());
        erpSellerStoreEmpowerMapper.insertOrUpdate(storeEmpower);
        empowerExtendMapper.insertOrUpdate(storeEmpowerExtend);
        return R.ok("同步成功");
    }

    /**
     * 同步token
     */
    @GetMapping("/synchronizationTokenByStoreUserName")
    public R<Object> synchronizationTokenByStoreUserName(String storeUserName) {
        try{
            ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStoreEmpower>()
                            .eq(ErpSellerStoreEmpower::getStoreUserName,storeUserName)
            );
            //调用接口，上老库里查询redis
            String body = HttpSendUtils.getReturnGetBody("https://pbb2c.com/erp-api/gather/test/synchronizationToken/" + store.getId().toString());
            if (!body.contains("200")) {
                System.out.println(store.getStoreUserName() + "  -  " + store.getId() + "同步失败");
                return R.fail("同步失败");
            } else {
                System.out.println(store.getStoreUserName() + "  -  " + store.getId() + "同步成功");
            }
            JSONObject bodyObj = JSONObject.parseObject(body).getJSONObject("msg");
            RedisUtils.setCacheObject(ACCESS_TOKEN_KEY + store.getStoreUserName(), bodyObj.toJSONString());
            RedisUtils.setCacheObject(ACCESS_TOKEN_KEY + store.getId(), bodyObj.toJSONString());
//        Object storeAliasObject = RedisUtils.getCacheObject(ACCESS_TOKEN_KEY + store.getStoreAlias());
//        Object storeIdObject = RedisUtils.getCacheObject(ACCESS_TOKEN_KEY + store.getStoreId());
            //返回信息保存redis
        }catch (Exception e){
            return R.fail("同步token失败");
        }
        return R.ok("同步token成功");
    }




    public static String getReturnGetBody(String url) {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet post = new HttpGet(url);
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Encoding", "gzip");
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(post);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HttpEntity response = httpResponse.getEntity();
        try {
            return EntityUtils.toString(response, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
